package com.yl.ydk.presenter.impl

import android.content.Context
import android.content.Intent
import androidx.recyclerview.widget.LinearLayoutManager
import com.yl.ydk.R
import com.yl.ydk.api.Api
import com.yl.ydk.base.BasePresenter
import com.yl.ydk.bean.LiveListBean
import com.yl.ydk.presenter.contract.LiveListActivityContract
import com.yl.ydk.ui.activity.LiveDetailActivity
import com.yl.ydk.ui.adapter.LiveListAdapter
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

class LiveListActivityImpl : BasePresenter<LiveListActivityContract.View>(),
    LiveListActivityContract.Presenter<LiveListActivityContract.View> {

    override fun getLiveList(context: Context) {
        showLoadingDialog(context)
        addSubscrebe(
            Api.getInstance()?.getLiveList()
                ?.observeOn(AndroidSchedulers.mainThread())
                ?.subscribeOn(Schedulers.io())
                ?.unsubscribeOn(Schedulers.io())
                ?.subscribe(object : Observer<LiveListBean?> {
                    override fun onCompleted() {}
                    override fun onError(e: Throwable) {
                        dismissLoadingDialog()
                        mView?.showError(e.toString())
                    }

                    override fun onNext(t: LiveListBean?) {
                        dismissLoadingDialog()
                        if (t?.data != null && t.code == 200) {
                            mView?.getRvLiveList()?.let {
                                val adapter = LiveListAdapter(t.data.list.toMutableList())
                                it.adapter = adapter
                                val manager = LinearLayoutManager(context)
                                manager.orientation = LinearLayoutManager.HORIZONTAL
                                it.layoutManager = manager
                                adapter.onListItemClick(object : LiveListAdapter.onListItemClick {
                                    override fun onListItemClick(item: LiveListBean.DataX?) {
                                        mView?.getActivity()?.let {
                                            val intent = Intent(it, LiveDetailActivity::class.java)
                                            intent.putExtra("live_id", item?.id)
                                            it.startActivityIn(intent, it)
                                        }
                                    }
                                })
                            }
                        } else {
                            mView?.showError(context.getString(R.string.connectFailure))
                        }
                    }
                })
        )
    }

}